﻿using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using SMSManager.Commn.Interfaces;
using SMSManager.WpfClient.Properties;

namespace SMSManager.WpfClient
{
	/// <summary>
	/// 	Interaction logic for App.xaml
	/// </summary>
	public partial class App : Application
	{
		private static Bootstrapper _bootstrapper;

		public App()
		{
			Startup += ApplicationStartup;
			Exit += AppilcationExit;
#if !DEBUG
			AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
			TaskScheduler.UnobservedTaskException += TaskSchedulerUnobservedTaskException;
#endif
		}

		private static void AppilcationExit(object sender, ExitEventArgs e)
		{
			var smsSettings = _bootstrapper.CompositionContainer.GetExportedValue<ISMSSettings>();
			smsSettings.Save();
			Settings.Default.Save();
		}

		private static void ApplicationStartup(object sender, StartupEventArgs e)
		{
			_bootstrapper = new Bootstrapper();
			_bootstrapper.Run();
		}

		private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			HandleException((Exception) e.ExceptionObject);
		}

		private static void HandleException(Exception e)
		{
			using (var sw = new StreamWriter("error.log", true, Encoding.UTF8))
			{
				sw.WriteLine("---------------------------------------------------------------------");
				sw.WriteLine(DateTime.Now.ToString());
				sw.WriteLine("---------------------------------------------------------------------");
				sw.WriteLine(e.ToString());
			}
			MessageBox.Show(e.GetType().FullName + "\r\n" + "Please check the log file.");
		}

		private static void TaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
		{
			HandleException(e.Exception);
		}
	}
}